using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;

public class AssetInfoWindow : EditorWindow
{
    private Object draggedAsset;
    private Vector2 scrollPos;

    [MenuItem("Tools/Asset Info Window")]
    static void Init()
    {
        var window = GetWindow<AssetInfoWindow>();
        window.titleContent = new GUIContent("Asset Info");
        window.Show();
    }

    void OnGUI()
    {
        DrawDragDropArea();
        DisplayAssetInfo();
    }

    #region 拖拽区域
    void DrawDragDropArea()
    {
        // 绘制可拖拽区域
        Rect dragArea = GUILayoutUtility.GetRect(0, 35, GUILayout.ExpandWidth(true));
        GUI.Box(dragArea, "拖拽资产到此区域", EditorStyles.helpBox);

        // 处理拖拽事件
        Event currentEvent = Event.current;
        switch (currentEvent.type)
        {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!dragArea.Contains(currentEvent.mousePosition)) return;

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                if (currentEvent.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    HandleDraggedAssets();
                }
                currentEvent.Use();
                break;
        }
    }
    #endregion

    #region 处理拖拽的资产
    void HandleDraggedAssets()
    {
        // 获取拖拽路径（支持多文件）
        List<string> paths = DragAndDrop.paths.ToList();

        // 过滤非 Assets 目录文件
        paths = paths.Where(p => p.StartsWith("Assets/")).ToList();
        if (paths.Count == 0) return;

        // 加载第一个有效资产
        string assetPath = paths[0];
        draggedAsset = AssetDatabase.LoadAssetAtPath<Object>(assetPath);

        if (draggedAsset == null)
        {
            Debug.LogError($"无法加载资产: {assetPath}");
        }
    }
    #endregion

    #region 显示资产信息
    void DisplayAssetInfo()
    {
        if (draggedAsset == null) return;

        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

        // 显示基础信息
        EditorGUILayout.LabelField("资产名称", draggedAsset.name);
        EditorGUILayout.LabelField("类型", draggedAsset.GetType().ToString());
        EditorGUILayout.LabelField("路径", AssetDatabase.GetAssetPath(draggedAsset));

        // 显示预览图（如果有）
        Texture2D preview = AssetPreview.GetAssetPreview(draggedAsset);
        if (preview != null)
        {
            GUILayout.Label("预览");
            GUILayout.Label(preview, GUILayout.Width(64), GUILayout.Height(64));
        }

        EditorGUILayout.EndScrollView();
    }
    #endregion
}